<template>
  <md-nav-bar title="购买广告位" backgroundColor="#ffffff" />
  <!-- 顶部tab -->
  <view class="adbuy-tab" :style="{ top: data.topTotalHeight }">
    <view :class="['tab-item', tabIndex === 0 ? 'active' : '']" @click="tabIndex = 0">购买</view>
    <view :class="['tab-item', tabIndex === 1 ? 'active' : '']" @click="tabIndex = 1">已购</view>
  </view>
  <view class="adbuy-container">
    <!-- 广告位卡片 -->
    <view v-if="tabIndex === 0">
      <view class="ad-card">
        <image class="ad-img" :src="data.config?.url" mode="aspectFill" />
        <view class="ad-info">
          <view class="ad-title">{{ data.config?.title }}</view>
          <view class="ad-desc">{{ data.config?.description }}</view>
          <view class="ad-price">
            <text class="ad-price-num">¥{{ formatUnitCentToYuan(data.config?.price, 2) + '元/' + data.config?.day + "天" }}</text>
          </view>
        </view>
      </view>

      <!-- 购买区域 -->
      <view class="buy-panel">
        <view class="buy-remain">
          当前还剩余
          <text class="remain-num">{{ data.config?.quantity }}</text>
          个位置可购买
        </view>
        <view class="buy-row">
          <view class="buy-label">购买数量</view>
          <input class="buy-input" type="number" v-model="buyCount" />
        </view>
        <view class="bug-hint">购买后在“<text style="color: #0c61f6">已购</text>”列表中设置推广歌曲</view>
        <button class="buy-btn"
                :class="{ 'ios-disabled': isIOS }"
                :disabled="isIOS"
                @click="onBuy">{{ isIOS ? 'IOS暂不支持' : '确认购买' }}</button>
      </view>
    </view>
    <!-- 已购tab -->
    <view v-if="tabIndex === 1">
      <md-page-list :api="api.Ad.buyList" :params="{ memberId: data.memberId }" @change="pageChange" ref="pageRef">
        <view v-for="item in data.buyList" :key="item.spaceName" class="bought-card">
          <view class="bought-header">
            <view class="bought-title">{{ item.spaceName }}</view>
            <view class="bought-price">￥{{ formatUnitCentToYuan(item.price, 2) }}</view>
          </view>
          <view class="bought-row">
            <view class="bought-label">购买时间</view>
            <view class="bought-value">{{ item.buyTime }}</view>
          </view>
          <view class="bought-row">
            <view class="bought-label">有效期</view>
            <view class="bought-value">{{ item.lifespan }}</view>
          </view>
          <view class="bought-song">
            <image class="song-img" :src="item.coverUrl" mode="aspectFill" />
            <view class="song-title">{{ item.musicName }}</view>
            <button :class="['set-btn', { disabled: !item?.setting }]" @click="onSet(item)">
              {{ !item?.setting ? '已过期' : '设置' }}
            </button>
          </view>
        </view>
      </md-page-list>
    </view>
  </view>
</template>

<script lang="ts" setup>
import {computed, reactive, ref} from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
// 接口
import api from '@/api';
import type { Ad } from '@/api/data';
import { Toast, formatUnitCentToYuan } from '@/utils/util';
const { statusBarHeight, platform } = uni.getSystemInfoSync();

const data = reactive({
  topTotalHeight: `calc(${statusBarHeight}px + ${platform === 'android' ? 48 : 44}px)`,
  memberId: -1,
  config: {} as Ad.Config.Data,
  buyList: [] as Ad.BuyList.ListVo[],
  currentSpaceId: -1, // 当前广告位id
});
const pageRef = ref<any>(null);

const tabIndex = ref(0);
const buyCount = ref(1);
const isIOS = computed(() => {
  const {system} = wx.getSystemInfoSync()
  const config = uni.getStorageSync('config');
  const iosShowFlag = config?.iosShowFlag || false;
  return system.toLowerCase().includes('ios') && iosShowFlag;
});


async function onBuy() {
  if (isIOS.value) {
    return;
  }
  if (buyCount.value > data.config?.quantity) {
    Toast('购买数量超过可购买数量！');
    return;
  }
  const order = await fetchCreateOrderId();
  if (order?.payOrderId) {
    fetchSubmit(order.payOrderId);
  }
}

function onSet(item: Ad.BuyList.ListVo) {
  if (!item.setting) {
    return;
  }
  data.currentSpaceId = item.spaceId;
  uni.navigateTo({ url: '/pages/sub/my/selectMyMusic' });
}

// 已购广告位列表
const pageChange = (list: Ad.BuyList.ListVo[]) => {
  data.buyList = list;
};

/**
 * 接口相关
 */
const fetchGetConfig = async () => {
  try {
    const res = await api.Ad.config();
    data.config = res.data;
  } catch (e) {}
};

// 设置广告位
const fetchSetAd = async (musicId: number) => {
  try {
    await api.Ad.set({
      musicId,
      spaceId: data.currentSpaceId,
    });
    pageRef.value?.onRefresh();
  } catch (e) {}
};

// 创建订单
const fetchCreateOrderId = async () => {
  try {
    const res = await api.Ad.creatOrder({
      memberId: data.memberId,
      num: +buyCount.value,
    });
    return res?.data;
  } catch (error) {}
  return undefined;
};

// 通过订单，提交支付
const fetchSubmit = async (orderId: number) => {
  const openid = uni.getStorageSync('auth')?.openid;
  try {
    const res = await api.Pay.submit({
      id: orderId,
      channelCode: 'wx_lite', // 微信支付
      channelExtras: {
        openid,
      },
    });
    const payConfig = JSON.parse(res.data?.displayContent || '');
    // 线上 弹出微信支付
    uni.requestPayment({
      provider: 'wxpay',
      orderInfo: {},
      nonceStr: payConfig?.nonceStr, // 随机字符串
      package: payConfig?.packageValue, // 固定值
      signType: payConfig?.signType,
      timeStamp: payConfig?.timeStamp, // 时间戳（单位：秒）
      paySign: payConfig?.paySign, // 签名，这里用的 MD5/RSA 签名
      async success(res) {
        uni.showModal({
          title: '提示',
          content: '充值成功',
          showCancel: false,
          success: res => {
            if (res.confirm) {
              fetchGetConfig();
            }
          },
        });
      },
      fail(e) {
        console.log('pay fail::', e);
        fetchPayCancelOrder(orderId); // 取消订单
      },
    });
  } catch (error) {}
  return undefined;
};

// 取消订单
const fetchPayCancelOrder = async (payOrderId: number) => {
  try {
    await api.Ad.payCancel({
      memberId: data.memberId,
      payOrderId,
    });
    Toast('订单取消');
  } catch (e) {}
};

onLoad((options: any) => {
  data.memberId = uni.getStorageSync('auth')?.userId;
  fetchGetConfig();
});

onShow(() => {
  // 接收下一个页面带回来的参数
  uni.$once('select_myMusic', function (data) {
    if (data?.musicId) {
      fetchSetAd(data.musicId);
    }
  });
});
</script>

<style lang="scss" scoped>
.adbuy-container {
  background: #f5f8f7;
  padding-bottom: 32rpx;
}
.adbuy-tab {
  display: flex;
  background: #fff;
  border-bottom: 2rpx solid #f0f0f0;
  margin-bottom: 8rpx;
  position: sticky;
  z-index: 1;
}
.tab-item {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  color: #222;
  padding: 32rpx 0 18rpx 0;
  font-weight: 500;
  position: relative;
  opacity: 0.8;
}
.tab-item.active {
  color: #1fa37a;
  opacity: 1;
}
.tab-item.active::after {
  content: '';
  display: block;
  width: 48rpx;
  height: 6rpx;
  background: #1fa37a;
  border-radius: 3rpx;
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
}
.ad-card {
  display: flex;
  background: #fff;
  border-radius: 32rpx;
  margin: 24rpx 24rpx 0 24rpx;
  padding: 24rpx 24rpx 24rpx 24rpx;
  align-items: center;
}
.ad-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 16rpx;
  background: #eee;
  margin-right: 18rpx;
  flex-shrink: 0;
}
.ad-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.ad-title {
  font-size: 32rpx;
  color: #222;
  font-weight: 600;
  margin-bottom: 8rpx;
}
.ad-desc {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 12rpx;
}
.ad-price {
  font-size: 30rpx;
  color: #00785a;
  font-weight: 600;
}
.ad-price-num {
  color: #00785a;
  font-size: 32rpx;
  font-weight: 600;
}
.ad-price-unit {
  color: #00785a;
  font-size: 28rpx;
  margin-left: 2rpx;
}
.buy-panel {
  background: #fff;
  border-radius: 32rpx;
  margin: 24rpx 24rpx 0 24rpx;
  padding: 32rpx 24rpx 48rpx 24rpx;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.buy-remain {
  font-size: 28rpx;
  color: #222;
  margin-bottom: 32rpx;
}
.remain-num {
  color: #00785a;
  font-size: 46rpx;
  font-weight: 600;
  margin: 0 4rpx;
}
.buy-row {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
  width: 100%;
}
.buy-label {
  font-size: 28rpx;
  color: #222;
  margin-right: 24rpx;
  min-width: 120rpx;
}
.buy-input {
  flex: 1;
  height: 64rpx;
  border: 2rpx solid #bbb;
  border-radius: 12rpx;
  font-size: 32rpx;
  color: #222;
  background: #fff;
  padding: 0 24rpx;
  text-align: center;
}
.bug-hint {
  font-size: 26rpx;
  color: #888;
  margin-top: 58rpx;
  text-align: center;
  width: 100%;
}
.buy-btn {
  width: 100%;
  height: 90rpx;
  background: #006a56;
  color: #fff;
  font-size: 36rpx;
  border-radius: 60rpx;
  font-weight: 600;
  border: none;
  margin-top: 32rpx;
  box-shadow: 0 4rpx 16rpx 0 #e0e0e0;
}
.bought-card {
  background: #fff;
  border-radius: 32rpx;
  margin: 24rpx 24rpx 0 24rpx;
  padding: 28rpx 24rpx 24rpx 24rpx;
  display: flex;
  flex-direction: column;
}
.bought-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}
.bought-title {
  font-size: 32rpx;
  color: #222;
  font-weight: 600;
}
.bought-price {
  font-size: 32rpx;
  color: #00785a;
  font-weight: 600;
}
.bought-row {
  display: flex;
  align-items: center;
  margin-bottom: 6rpx;
}
.bought-label {
  font-size: 26rpx;
  color: #888;
  min-width: 120rpx;
}
.bought-value {
  font-size: 26rpx;
  color: #222;
}
.bought-song {
  background: #f3f3f3;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  margin-top: 18rpx;
  padding: 18rpx 18rpx 18rpx 18rpx;
}
.song-img {
  width: 64rpx;
  height: 64rpx;
  border-radius: 12rpx;
  background: #eee;
  margin-right: 18rpx;
  flex-shrink: 0;
}
.song-title {
  flex: 1;
  font-size: 28rpx;
  color: #222;
  font-weight: 500;
  margin-right: 18rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.set-btn {
  background: #006a56;
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  padding: 0 36rpx;
  height: 56rpx;
  line-height: 56rpx;
  font-weight: 500;
  border: none;
  box-shadow: none;
  &.disabled {
    opacity: 0.5;
  }
}
</style>
